import axios from "axios";
import { getToken, removeToken } from "./cookie";

//不同的功能，通过axios请求的是不同的接口

axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";

const service = axios.create({
    baseURL: "/dev-api", //提取出公共的接口地址
    timeout: 5000,    //超时时间，单位毫秒
})

//请求拦截器
service.interceptors.request.use(
    (config) => { //修改请求配置对象，给请求头添加token信息
        if(getToken()) {
            config.headers["Authorization"] = "Bearer " + getToken();
        }   
        return config;
    },
    (error) => {
        console.log(error);
        Promise.reject(error);
    }
);


//响应拦截器
service.interceptors.response.use(
    //响应成功回调
    (res) => {
        // 未设置状态码则默认成功状态
        const code = res.data.code;
        const msg = res.data.msg;
        if(code === 3001) {  //token过期或者是非法token
            ElMessage.error(msg);
            removeToken();    //清除cookie中的token
            router.push('/b-oj/login');
            return Promise.reject(new Error(msg));

        }
        else if (code !== 1000) {
            ElMessage.error(msg);
            return Promise.reject(new Error(msg));
            
        } else {
            return Promise.resolve(res.data);
        }
    },
    //响应失败回调
    (error) => {
        return Promise.reject(error);
    }
);

export default service